//
//  RegistThreeViewController.m
//  XDCommonApp
//
//  Created by wanglong8889@126.com on 14-3-7.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "RegistThreeViewController.h"
#import "XDTools.h"
#import "XDHeader.h"
#import "LoginViewController.h"
//#import "MobClick.h"
#import "Base64.h"
#import "WLSingleton.h"
#define XZB     65
@interface RegistThreeViewController ()

@end

@implementation RegistThreeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initViews];
	// Do any additional setup after loading the view.
}
-(void)initViews{
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelPan)];
    [self.contentView addGestureRecognizer:tap];
    [self changeFrameWhenHiddenNavigationBar];
    headerView = [[UIImageView alloc] initWithFrame:CGRectMake(XZB, 130, 55, 55)];
    headerView.image = [UIImage imageNamed:@"personal_setting"];
    
    UIImageView *pointView = [[UIImageView alloc] initWithFrame:CGRectMake(122, 22, 72, 11)];
    pointView.image = [UIImage imageNamed:@"three_point"];
    [self.contentView addSubview:pointView];
    
    UIButton *addHeadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addHeadBtn setTitle:@"添加头像" forState:UIControlStateNormal];
    [addHeadBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    addHeadBtn.frame = CGRectMake(headerView.frame.origin.x+headerView.frame.size.width+14,170, 60, 17);
    addHeadBtn.titleLabel.font = [UIFont systemFontOfSize:13.0];
    [addHeadBtn addTarget:self action:@selector(addHeadAction) forControlEvents:UIControlEventTouchUpInside];
    
    nickTf = [[UITextField alloc] initWithFrame:CGRectMake(XZB, headerView.frame.origin.y+headerView.frame.size.height+15,187, 28)];
    nickTf.borderStyle = UITextBorderStyleLine;
    nickTf.backgroundColor =  RGBA(168, 168, 168, 1.0);
    nickTf.textColor = [UIColor whiteColor];
    if (IOS7) {
        nickTf.tintColor = [UIColor whiteColor];
        
    }
    nickTf.delegate = self;
    nickTf.font = [UIFont systemFontOfSize:13.0];
    nickTf.returnKeyType = UIReturnKeyDone;
    nickTf.placeholder = @"请输入昵称";
    nickTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.contentView addSubview:nickTf];
    
    UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(XZB, nickTf.frame.origin.y+nickTf.frame.size.height+10, 192, 15)];
    tipLabel.backgroundColor = [UIColor clearColor];
    tipLabel.font = [UIFont systemFontOfSize:12.0];
    tipLabel.text = @"昵称一旦确定将不可修改";
    
    UILabel *startLabel = [[UILabel alloc] initWithFrame:CGRectMake(XZB+50, nickTf.frame.origin.y+nickTf.frame.size.height+62, 64, 18)];
    startLabel.backgroundColor = [UIColor clearColor];
    startLabel.font = [UIFont systemFontOfSize:15.0];
    startLabel.text = @"开始使用";
    
    UIImageView *arrowimageView = [[UIImageView alloc] initWithFrame:CGRectMake(startLabel.frame.origin.x+startLabel.frame.size.width+5, startLabel.frame.origin.y, 12, 18)];
    arrowimageView.image = [UIImage imageNamed:@"launh_sure"];
    
    UIButton *startBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    startBtn.frame = CGRectMake(XZB+50, nickTf.frame.origin.y+nickTf.frame.size.height+60, 90, 22);
    [startBtn addTarget:self action:@selector(startAcion) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(8, 0, 45, 45);
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *bImageView = [[UIImageView alloc] initWithFrame:CGRectMake(24, 17, 11, 18)];
    bImageView.image = [UIImage imageNamed:@"left_back"];
    [self.contentView addSubview:bImageView];
    [self.contentView addSubview:backBtn];
    
    [self.contentView addSubview:headerView];
    [self.contentView addSubview:addHeadBtn];
    [self.contentView addSubview:nickTf];
    [self.contentView addSubview:tipLabel];
    [self.contentView addSubview:startLabel];
    [self.contentView addSubview:arrowimageView];
    [self.contentView addSubview:startBtn];
    
    
}
//添加头像
-(void)addHeadAction{
    [self photoImageTapAction:@"上传照片"];
}
-(void)cancelPan{
    [nickTf resignFirstResponder];
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [nickTf resignFirstResponder];
    return YES;
}
//开始使用
-(void)startAcion{
    DDLOG(@"hehe");
    if (nickTf.text.length==0) {
        [XDTools showTips:@"昵称不能为空" toView:self.contentView];
    }
//        else if (portal.length == 0){
//        [XDTools showTips:@"上传头像失败" toView:self.contentView];
//    }
        else {
        [self giveServiceDatas];
    }
}
-(void)giveServiceDatas{
    if ([XDTools NetworkReachable]){
        NSString *body = [NSString stringWithFormat:@" <RegisterThree xmlns=\"http://tempuri.org/\">"
                          "<Uid>%@</Uid>"
                          "<pwd>%@</pwd>"
                          "<phone>%@</phone>"
                          "<username>%@</username>"
                          "<portal>%@</portal>"
                          "</RegisterThree>",[WLSingleton sharedManager].Uid,[WLSingleton sharedManager].pwd,[WLSingleton sharedManager].phoneName,nickTf.text,portal];
        
        __weak ASIFormDataRequest *request = [XDTools postRequestWithDict:body API:REGISTERTHREE];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            //[XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];
            // NSDictionary *tempDic = [XDTools  JSonFromString:responseString];
            DDLOG(@"responseString:%@", responseString);
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            int statusCode = [request responseStatusCode];
            NSString *soapAction = [[request requestHeaders] objectForKey:@"SOAPAction"];
            
            NSArray *arraySOAP =[soapAction componentsSeparatedByString:@"/"];
            int count = [arraySOAP count] - 1;
            NSString *methodName = [arraySOAP objectAtIndex:count];
            
            // Use when fetching text data
            NSString *result = nil;
            if (statusCode == 200) {
                //表示正常请求
                result = [SoapXmlParseHelper SoapMessageResultXml:responseString ServiceMethodName:methodName];
                NSDictionary  *responseDict = [XDTools JSonFromString:result];
                DDLOG(@"respodic = %@",responseDict);
                if ([[responseDict objectForKey:@"code"] intValue]==0){
                    [WLSingleton sharedManager].Uid = [responseDict objectForKey:@"Uid"];
                    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                    [user setObject:nickTf.text forKey:kMY_USER_NICKERNAME];
                    [XDTools showTips:@"注册成功" toView:self.contentView];
                    LoginViewController *a = [self.navigationController.viewControllers objectAtIndex:1];
                    [self.navigationController popToViewController:a animated:YES];
                    
                }else{
                    [XDTools showTips:@"昵称格式不对" toView:self.contentView];
                }
            }
        }];
        
        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
        }];
        
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }

}
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma  mark ---------------ActionSheet ---------------
- (void)photoImageTapAction:(NSString *)title
{
    photoActionSheet = [[UIActionSheet alloc] initWithTitle:title delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从手机相册选择", nil];
    [photoActionSheet showInView:self.contentView];
}

-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    DDLOG(@"buttonIndex = %d", buttonIndex);
    if (buttonIndex == 0) {
        [self selectIncameraAction];
    }else if (buttonIndex == 1){
        [self selectInPhotoAlbumAction];
    }
}

//从本地相机选取图片
- (void)selectInPhotoAlbumAction
{
    imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.navigationBar.tintColor = [UIColor blackColor];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //本地相机
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.allowsEditing = YES;
    
    [self presentViewController:imagePicker animated:YES completion:^{
        
    }];
}

//照相选取图片
- (void)selectIncameraAction
{
    imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.navigationBar.tintColor = [UIColor blackColor];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.allowsEditing = YES;
    [self presentViewController:imagePicker animated:YES completion:^{
        
    }];
}

#pragma mark ----------------imagePickerDelegate-----------------------------
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    isPhotoHadEdit = YES;
    
    //获得编辑过的图片
    if (isHeaderPhoto) {
        //头像
        isHeaderPhoto = NO;
        UIImage * image = [info objectForKey: @"UIImagePickerControllerEditedImage"];
        UIImageWriteToSavedPhotosAlbum(image, nil, nil,nil);
        headerView.image = [UIImage imageNamed:@"User_profile_default_detail_head"];
        [self upLoadImage:image];
        headerView.image = image;
    }else{
        //相册
        UIImage * image = [info objectForKey: @"UIImagePickerControllerOriginalImage"];
        [self upLoadImage:image];
        headerView.image = image;
    }
    
}

- (void)showProcessVC:(UIImage*)image
{
//    ProcessImageViewController * processVC = [[ProcessImageViewController alloc]init];
//    processVC.image = image;
//    [self.navigationController pushViewController:processVC animated:YES];
}


#pragma mrke --------------------上传图片-----------------------
- (void)upLoadImage:(UIImage*)image
{
//    [MobClick event:@"upload_image"];
    
    if (image ==nil) {
        return;
    }
    NSDate * date = [NSDate date];
    DDLOG(@"date:%@",date);
    double time = [date timeIntervalSince1970];
    int timex = time/1;
    NSString * postTime = [NSString stringWithFormat:@"%d",timex];
    DDLOG(@"postTime:%@",postTime);
    NSData *data = [XDTools compressImage:image];
    NSString * postImage = [Base64 encode:data];
    
    NSString * dataLength = [NSString stringWithFormat:@"%d",[data length]];
    DDLOG(@"dataLength:%@", dataLength);
    if ([XDTools NetworkReachable]){
        NSString *body = [NSString stringWithFormat:@" <UploadFile xmlns=\"http://tempuri.org/\">"
                          "<fs>%@</fs>"
                          "<FileName>%@</FileName>"
                          "</UploadFile>",postImage,[NSString stringWithFormat:@"%@.jpg",[WLSingleton sharedManager].Uid]];
        
        __weak ASIFormDataRequest *request = [XDTools postRequestWithDict:body API:UPLOADFILE];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            //[XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];
            // NSDictionary *tempDic = [XDTools  JSonFromString:responseString];
            DDLOG(@"responseString:%@", responseString);
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            int statusCode = [request responseStatusCode];
            NSString *soapAction = [[request requestHeaders] objectForKey:@"SOAPAction"];
            
            NSArray *arraySOAP =[soapAction componentsSeparatedByString:@"/"];
            int count = [arraySOAP count] - 1;
            NSString *methodName = [arraySOAP objectAtIndex:count];
            
            // Use when fetching text data
            NSString *result = nil;
            if (statusCode == 200) {
                //表示正常请求
                result = [SoapXmlParseHelper SoapMessageResultXml:responseString ServiceMethodName:methodName];
                NSDictionary  *responseDict = [XDTools JSonFromString:result];
                DDLOG(@"respodic = %@",responseDict);
                if ([[responseDict objectForKey:@"code"] intValue]==0){
                    portal = [responseDict objectForKey:@"url"];
                }else{
                    [XDTools showTips:@"头像上传失败" toView:self.contentView];
                }
            }
        }];
        
        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
        }];
        
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }

    

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
